package com.example.resubmit.aspect;

import com.example.resubmit.annotation.Resubmit;
import com.example.resubmit.util.ResubmitLock;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Log4j2
@Aspect
@Component
public class ResubmitDataAspect {

    private final static String DATA = "data";
    private final static Object PRESENT = new Object();

    @Around("@annotation(com.example.resubmit.annotation.Resubmit)")
    public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        // 获取注解信息
        Resubmit annotation = method.getAnnotation(Resubmit.class);
        int delaySeconds = annotation.delaySeconds();
        // 参数列表
        Object[] pointArgs = joinPoint.getArgs();
        // 获取第一个参数
//        Object firsetParam = pointArgs[0];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < pointArgs.length; i++) {
            Object pointArg = pointArgs[i];
            sb.append(pointArg);
        }
        String strKey = sb.toString();
        //将所有参数进行md5加密做为key存到hashMap中,
        String key = ResubmitLock.handleKey(strKey);
        //开始锁 如果在hashMap中选找到该key代表之前提交过表单, 不给再次进入该方法直接返回友好提示, 需要等待unlock
        boolean lock = false;
        try {
            lock = ResubmitLock.getInstance().lock(key, PRESENT);
            // 如果key不存在放行,否则
            if (lock) {
                return joinPoint.proceed();
            } else {
                //
                return String.format("你已经提交过这些信息:%s", strKey);
            }
        } finally {
            // 设置解锁key和解锁时间
            ResubmitLock.getInstance().unLock(lock, key, delaySeconds);
        }
    }
}
